import network
import urequests
import ujson
import ble
from ble import ESP32_BLE
print("进入boot")
# WiFi连接配置
WIFI_SSID = "lvshun"  # WIFI 名称
WIFI_PASSWORD = "lvshun123"  # WIFI 密码

# ============================================================================== #

# 文件列表（假设这里是你需要检测更新的7个文件）
FILES_TO_UPDATE = [
    {"name": "main.py", "url": "https://gitee.com/yutakagen/OTA-updates/raw/master/lv-box-ota-dev/main.py"},
    {"name": "rgb.mpy", "url": "https://gitee.com/yutakagen/OTA-updates/raw/master/lv-box-ota-dev/rgb.mpy"},
    {"name": "ble.mpy", "url": "https://gitee.com/yutakagen/OTA-updates/raw/master/lv-box-ota-dev/ble.mpy"},
    {"name": "handgrip.mpy",
        "url": "https://gitee.com/yutakagen/OTA-updates/raw/master/lv-box-ota-dev/handgrip.mpy"},
    {"name": "buzzer.mpy",
        "url": "https://gitee.com/yutakagen/OTA-updates/raw/master/lv-box-ota-dev/buzzer.mpy"},
    {"name": "pid.mpy", "url": "https://gitee.com/yutakagen/OTA-updates/raw/master/lv-box-ota-dev/pid.mpy"},
    {"name": "pwm.mpy", "url": "https://gitee.com/yutakagen/OTA-updates/raw/master/lv-box-ota-dev/pwm.mpy"}
]  # 文件网址
# ============================================================================== #

'''
从flash中获取wifi名称和wifi密码
'''


def Get_wifi_names():
    global WIFI_SSID, WIFI_PASSWORD
    try:
        with open("Wifi_flash_data.json", "r") as f:
            json_data = f.read()
            # 将JSON数据转换为字典
            data = ujson.loads(json_data)
            # 读取变量的值
            WIFI_SSID = data["Wifi_name"]
            WIFI_PASSWORD = data["Wifi_pass"]
    except Exception as e:
        print("内存中不存在wifi名称和密码:", str(e))


# ============================================================================== #

'''
连接WIFI
'''


def connect_to_wifi():
    try:
        wlan = network.WLAN(network.STA_IF)
        wlan.active(True)
        if not wlan.isconnected():
            print("Connecting to WiFi network...")
            wlan.connect(WIFI_SSID, WIFI_PASSWORD)
            while not wlan.isconnected():
                pass
        print("WiFi connected")
        print("IP address:", wlan.ifconfig()[0])
    except Exception as e:
        Wifi_error_blue_send()
        print("WiFi connection error:", str(e))

# ============================================================================== #


'''
下载文件
'''


def download_file(file_url):
    print("Downloading file:", file_url)
    response = urequests.get(file_url)
    if response.status_code == 200:
        file_content = response.content
        print("File downloaded successfully")
        return file_content
    else:
        print("Failed to download file")

# ============================================================================== #


'''
更新文件
'''


def update_file(file_name, file_url):
    print("Updating file:", file_name)
    file_content = download_file(file_url)
    if file_content:
        try:
            with open(file_name, "w") as f:
                f.write(file_content)
            print("File updated successfully")
        except Exception as e:
            print("Failed to update file:", str(e))

# ============================================================================== #


'''
读取OTA文件的标志位
'''


def read_ota_file():
    try:
        with open("Ota_Boot_flash.json", "r") as f:
            json_data = f.read()
            ota_file = ujson.loads(json_data)
            return ota_file
    except Exception as e:
        print("Failed to read OTA file:", str(e))
        return None

# ============================================================================== #


'''
OTA更新文件
'''


def ota_update_files():
    print("OTA文件检测和更新开始")
    # 加载OTA文件
    ota_file = read_ota_file()

    if ota_file:
        # 检查是否需要更新文件
        need_update = False
        for file_info in FILES_TO_UPDATE:
            file_name = file_info["name"]
            ota_key = "Ota_" + file_name.split(".")[0]  # 构造OTA文件的键名
            update_flag = ota_file.get(ota_key, 0)  # 获取更新标志
            if update_flag == 1:
                need_update = True
                break

        if need_update:
            # 连接到WiFi网络
            Get_wifi_names()      # 读取wifi名称和密码
            connect_to_wifi()      # 连接wifi名称和密码
            wifi_connected = True

            if wifi_connected:
                # 更新文件
                for file_info in FILES_TO_UPDATE:
                    file_name = file_info["name"]
                    file_url = file_info["url"]
                    ota_key = "Ota_" + file_name.split(".")[0]  # 构造OTA文件的键名
                    update_flag = ota_file.get(ota_key, 0)  # 获取更新标志
                    if update_flag == 1:
                        update_file(file_name, file_url)
                    else:
                        print("无需更新")
            else:
                print("无法连接到WiFi网络")
        else:
            print("没有需要更新的文件")
    else:
        print("OTA文件不存在")


# ============================================================================== #
'''
回传报错信息
'''


def Wifi_error_blue_send():
    try:
        ble.send("lvi+" + "wifierror+")
    except Exception as e:
        print("Wifi_error_blue_send file:", str(e))
        return None


ota_update_files()
